#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, signal, os

global_debug = False
if "-d" in sys.argv:
    global_debug = True
    
def debug(msg, fr=None):
    if global_debug: 
        if fr: msg = "[%s] %s" % (fr, msg)
        print msg
    
if global_debug: debug("*** Debug output enabled ***", "app")

# find and create configuration directories
home_dir = os.path.expanduser("~")
config_dir = os.path.join(home_dir, ".flashftp")
if not os.path.isdir(config_dir):
    os.mkdir(config_dir)
queues_dir = os.path.join(config_dir, "queues")
if not os.path.isdir(queues_dir):
    os.mkdir(queues_dir)

# look for our "data" directory
possibilities = ("data", "../data", "/usr/local/lib/flashftp", 
    "/usr/lib/flashftp")
data_dir = None
for p in possibilities:
    if os.path.isdir(p) or os.path.islink(p):
        debug("data directory found: %s" % p, "app")
        data_dir = p
        break
if not data_dir:
    sys.stderr.write("[ERROR] data directory NOT found!\n")
    sys.exit(1)

# find files
config_file = os.path.join(config_dir, "flash.conf")
glade_file = os.path.join(data_dir, "flash.glade")
# if the glade file was not found we have nowhere to go
if not os.path.isfile(glade_file):
    sys.stderr.write("[ERROR] glade file not found, exiting.\n")
    sys.exit(1)

import pygtk
pygtk.require('2.0')
import gtk
from gtk import gdk
try:
    import dbus
except ImportError:
    dbus = None

import browser
import queue
import config
import ftp
import connectdialog
ftp.debugmsg = lambda m: debug(m, "ftp")


class StatusIcon(gtk.StatusIcon):
    def __init__(self, appinst):
        gtk.StatusIcon.__init__(self)
        
        self.appinst = appinst
        self.config = appinst.config
        
        self.set_from_file(os.path.join(data_dir, "flash-64.png"))


class FlashFTPApp:
    def __init__(self):
        self.browsers = []
        self.queues = []
        self.preferences_window = None
        self.connect_window = None
        self.status_icon = None
        
        self.config = config.Config()
        self.config.read()
        
        if self.config.getboolean("app", "statusicon"):
            self.status_icon = StatusIcon(self)
        
        gdk.threads_init()
        
        for q in os.listdir(queues_dir):
            self.new_queue(name=q, load=True)
        
    def close_window(self, window):
        """Called from a browser or queue to be removed.
        The object will be closed and dereferenced, and 
        hopefully released by the gc. TODO: Look into that."""
        if window in self.browsers:
            self.browsers.remove(window)
        elif window in self.queues:
            self.queues.remove(window)
        elif window is self.preferences_window:
            self.preferences_window = None
        elif window is self.connect_window:
            self.connect_window = None
        else:
            debug("Closing unknown window: %s" % window, "app")
        
        window.close()
        
        # exit on no windows
        if not (self.browsers or self.queues or self.preferences_window or \
            self.connect_window):
            self.config.write()
            gtk.main_quit()
        
    def new_browser(self, connect_dialog=False):
        """Open a new Browser."""
        b = browser.BrowserWindow(self)
        if connect_dialog:
            b.new_connect_dialog()
        self.browsers.append(b)
        return b
        
    def new_queue(self, name=None, load=False):
        """Open a new Queue.
        
        If load is True, attempt to load the queue from disk."""
        if load:
            store = queue.queue_from_disk(name)
        else:
            store = None
        if not name:
            if len(self.queues) == 0:
                name = "Queue"
            else:
                name = "Queue " + str(len(self.queues) + 1)
            
        q = queue.QueueWindow(self, name=name, store=store)
        self.queues.append(q)
        return q
        
    def new_preferences(self):
        """Open the preferences window, if not already open."""
        if self.preferences_window:
            debug("Preferences window already open!", "app")
            debug(str(self.preferences_window), "app")
        else:
            self.preferences_window = config.PreferencesWindow(self)
            return self.preferences_window
            
    def new_connect_dialog(self):
        """Open a Connect Dialog with no browser attached."""
        self.connect_window = connectdialog.ConnectDialog(self)
    
    def loop(self):
        gdk.threads_enter()
        try:
            gtk.main()
        except KeyboardInterrupt:
            print "Leaving on ^C"
        gdk.threads_leave()
    

if __name__ == "__main__":
    my = FlashFTPApp()
    my.new_connect_dialog()
    my.loop()
